# -*- coding: utf-8 -*-
# 创建时间：2021/7/16 15:55
from bs4 import BeautifulSoup
import requests
import time, math, random, json
import pymysql
import re
from influxdb import InfluxDBClient
import os
import psutil
from pyecharts.charts import Bar, Line, Liquid, Gauge, Grid

__author__ = 'LuckyHhy'
# 服务情况

def main():
    # 获取当前运行的pid
    p1 = psutil.Process(os.getpid())
    while True:
        a = psutil.virtual_memory().percent  # 内存占用率
        b = psutil.cpu_percent(interval=1.0)  # cpu占用率
        # json_body = [
        #     {
        #         "measurement": "cpu_load_short",
        #         "tags": {
        #             "host": "server01",
        #             "region": "us-west"
        #         },
        #         #"time": "2009-11-10T23:00:00Z",
        #         "fields": {
        #             "cpu": b,
        #             "mem": a
        #         }
        #     }
        # ]
        # 建立数据库连接
        db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='pay', charset='utf8')
        # 获取游标对象
        cursor = db.cursor()
        # 插入数据语句
        query = "insert into cpu_load_short (cpu, mem, createtime) values (%s,%s,%s)"

        # 当前时间
        tt = time.time()
        # 值
        values = (b, a, int(tt))

        cursor.execute(query, values)

        print(b)
        print(a)

        # 关闭游标，提交，关闭数据库连接
        # 如果没有这些关闭操作，执行后在数据库中查看不到数据

        cursor.close()
        db.commit()

        db.close()

        time.sleep(2)

    pass





if __name__ == '__main__':
     main()
